package com.yinhai.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.littlec.sdk.manager.CMIMHelper;
import com.lz.util.SystemParsUtils;
import com.lz.util.Utils;
import com.yinhai.asynctask.BaseTask;
import com.yinhai.cfg.AppConfig;
import com.yinhai.constant.Contact;
import com.yinhai.constant.UrlConstant;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.CMUtil;
import com.yinhai.util.DateUtil;
import com.yinhai.util.IMSI;
import com.yinhai.util.UuId;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * @author Juyon 程序入口类
 */
public class LoadingActivity extends Activity {
    private MyHandler handler;
    
    private Context context;
    
    private Intent mainIntent = null;
    
    private ContactUserServiceImpl cusi = null;
    
    private AQuery aq = null;
    
    private ProgressDialog mDialog;
    
    private File fileDownloaded;
    
    private boolean isDownloading = true;
    
    private Activity activity;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);
        context = this;
        aq = new AQuery(context);
        activity = this;
        SharedPreferences preferences =
                context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
            // Intent mainIntent = null;
        String uuid = preferences.getString("user_code", "");
//        if (!(uuid != null && (!"".equals(uuid)))) {
////        	 WebView localWebView = new WebView(this);
////             localWebView.loadUrl("file:///android_asset/listense.html");
////             new AlertDialog.Builder(this).setTitle("免责声明与软件许可协议").setView(localWebView).setNegativeButton(getString(2131361861), new j(this)).setPositiveButton(getString(2131361860), new i(this)).setOnCancelListener(new h(this)).show();
//             new AlertDialog.Builder(this).setTitle("免责声明与软件许可协议").setView(localWebView).setPositiveButton("同意",new OnClickListener(){
// 				@Override
// 				public void onClick(DialogInterface arg0, int arg1) {
// 					toSwit();
// 				}
//             	 
//              }).setNegativeButton("不同意", new OnClickListener(){
//
//				@Override
//				public void onClick(DialogInterface arg0, int arg1) {
//					activity.finish();
//				}
//             }).show();
//        } else {
//        	toSwit();
//        }
        toSwit();
        // c = new ContactUserServiceImpl(context);
       
    }
    
    private void toSwit() {
    	 HandlerThread myThread = new HandlerThread("myHandlerThread");
	        myThread.start();
	        handler = new MyHandler(myThread.getLooper());
	        handler.post(new Runnable() {
	            @Override
	            public void run() {
	                
	                try {
	                    // Thread.sleep(2 * 1000);
	                    SharedPreferences preferences =
	                        context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
	                    // Intent mainIntent = null;
	                    String uuid = preferences.getString("user_code", "");
	                    // Utils.showToast(context, "-------");
	                    if (uuid != null && (!"".equals(uuid))) {// 判断是否首次进入
	                        // Utils.showToast(context, uuid);
	                    	if(isConnect(context)) {
	                    		String contactGroupVersion = preferences.getString("onLineContactLastUpdateTime", "");
	                    		if(null == contactGroupVersion||"".equals(contactGroupVersion)) {
	                    			toLogin();
	                    		} else {
	                    			boolean flag = false;
	                    			int contactUpate = SystemParsUtils.getInstance(LoadingActivity.this).getInt("contactUpate");
	                    			if(0==contactUpate) {
	                    				//按天
	                    				flag = DateUtil.isAfterDays(new Date(),DateUtil.stringFormateDate(contactGroupVersion, DateUtil.DAY_TIME_FORMATE),"1");
	                    			} else if(1==contactUpate){
	                    				flag = DateUtil.isAfterDays(new Date(),DateUtil.stringFormateDate(contactGroupVersion, DateUtil.DAY_TIME_FORMATE),"2");
	                    			} else if(2 == contactUpate) {
	                    				//安周
	                    				flag = DateUtil.isAfterDays(new Date(),DateUtil.stringFormateDate(contactGroupVersion, DateUtil.DAY_TIME_FORMATE),"3");
	                    			}
	                    			if(flag) {
	                    				//需要更新数据
	                    				Toast.makeText(context, "集团通讯录数据有更新!", Toast.LENGTH_LONG).show();
	                    			}
	                    			toLogin();
	                    		}
//	                    		
	                    	} else {
	                    		//当不是首次登录并且没有网络时直接进入应用
	                    		noNetLogin();
	                    	}
	                       
	                        
	                    } else {// 是首次登录
	                    	//默认一周更新一次
	                    	SystemParsUtils.getInstance(LoadingActivity.this).setInt("contactUpate", 1);
	                        if (isConnect(context)) {
	                            // 初始化本地数据
	                            new BaseTask<String, String, String>(LoadingActivity.this) {
	                                
	                                @Override
	                                protected void onSuccess(String result) {
	                                    
	                                }
	                                
	                                @Override
	                                protected String doInBack(String... params)
	                                    throws Exception {
	                                    ContactUserServiceImpl c = new ContactUserServiceImpl(context);
	                                    c.initLocalContact();
	                                    return null;
	                                }
	                            }.execute();
	                            
	                           mainIntent = new Intent(LoadingActivity.this, SwitchActivity.class);
	                           startActivity(mainIntent);
	                           finish();
	                        } else {
	                            loginin();
	                        }
	                    }
	                    
	                    if (Utils.getDWTXL(context)) { // 是否自动同步 单位通讯录
//	                        LoginConfig log = LoginConfigUtil.getConfig(context);
//	                        ContactUserServiceImpl c = new ContactUserServiceImpl(context);
//	                        c.initOnlineContactLogin(log.getUsername());
	                    }
	                    
	                } catch (Exception e) {
//	                    Intent intent = new Intent(LoadingActivity.this, LoginValidateActivity.class);
//	                    startActivity(intent);
//	                    finish();
//	                    return;
	                	noNetLogin();
	                }
	                
	            }
	        });
    }
    
    private void toLogin() {
    	String url = UrlConstant.LOCAL_URI + UrlConstant.VSERSION;
        url = url + "?version=" + UrlConstant.VSERSION_NUM;
        aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject object, AjaxStatus status) {
                
                try {
                    
                    if (object != null) {
                        boolean isFlag = object.getBoolean("success");
                        if (isFlag) {
                            showUpdataDialog();
                        } else {
                            check();
                        }
                    }
                    
                } catch (Exception e) {
//                    Intent intent = new Intent(LoadingActivity.this, LoginValidateActivity.class);
//                    startActivity(intent);
//                    finish();
//                    return;
                	noNetLogin();
                }
                
            }
        });
    }
    
    private String getPhoneNumber(){  
        TelephonyManager mTelephonyMgr;  
        mTelephonyMgr = (TelephonyManager)  getSystemService(Context.TELEPHONY_SERVICE);   
        return mTelephonyMgr.getLine1Number();  
    }
    private void check() {
        // TODO: 2018/6/7
//        String url = UrlConstant.LOCAL_URI + UrlConstant.CHECK;

        String url = UrlConstant.LOCAL_URI + "appCascheck";
        String imsi = "";
        String flag = "";
        if (IMSI.getIMSI(context) != null) {
            imsi = IMSI.getIMSI(context);
            flag = "1";
        } else {
            imsi = UuId.getUUID();
            flag = "0";
        }
        aq = new AQuery(context);
        Map<String, String> params = new HashMap<String, String>();
        params.put("sim", imsi);
        params.put("flag", flag);
        params.put("user_phone",
            context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE).getString("name", ""));
        url =
            url + "?sim=" + imsi + "&flag=" + flag + "&user_phone="
                + context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE).getString("name", "");
        login(url);
    }
    
    class MyHandler extends Handler {
        
        public MyHandler(Looper looper) {
            super(looper);
        }
        
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    ContactUserServiceImpl c = new ContactUserServiceImpl(context);
                    c.initName();
                    break;
            }
        }
    }
    
    /**
     * 当没有网路的时候设置网路
     */
    private void loginin() {
        AlertDialog.Builder adg = new AlertDialog.Builder(context);
        adg.setTitle("网络错误:");
        adg.setMessage("是否手动设置网络？");
        adg.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                NetWorkStatus();
            }
        });
        adg.setNegativeButton("取消", null);
        adg.show();
    }
    
    private void NetWorkStatus() {
        startActivityForResult(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS), 0);
    }
    
    /**
     * 检查网路是否可用
     * 
     * @param context
     * @return
     */
    public static boolean isConnect(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity =
                (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
        }
        return false;
    }
    
    // 下载apk文件
    protected void downLoadApk() {
        mDialog = new ProgressDialog(context);
        mDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置风格为长进度条
        mDialog.setTitle("提示");// 设置标题 29
        mDialog.setMessage("正在下载中，请稍后");
        mDialog.setIndeterminate(false);// 设置进度条是否为不明确 false 就是不设置为不明确
        mDialog.setCancelable(false);// 设置进度条是否可以按退回键取消
        mDialog.setProgress(0);
        mDialog.incrementProgressBy(1); // 增加和减少进度，这个属性必须的
        mDialog.setMax(100);
        mDialog.setButton(DialogInterface.BUTTON_POSITIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                
                dialog.cancel();
                isDownloading = false;
                check();
            }
        });
        mDialog.show();
        
        new Thread() {
            @Override
            public void run() {
                try {
                    fileDownloaded =
                        getFileFromServer(UrlConstant.LOCAL_URI + "getAndroidApk?apkName=group-android-app", mDialog);
                    if (mDialog.getProgress() >= 100 || fileDownloaded != null) {
                        installApk(fileDownloaded);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
        
    }
    
    // 安装apk
    public void installApk(File file) {
        mDialog.dismiss();
        // 执行的数据类型
        Intent install = new Intent();
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        install.setAction(android.content.Intent.ACTION_VIEW);
        install.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        context.startActivity(install);
    }
    
    // 从服务器下载apk:
    public File getFileFromServer(String path, ProgressDialog pd)
        throws Exception {
        // 如果相等的话表示当前的sdcard挂载在手机上并且是可用的
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setConnectTimeout(5000);
            // 获取到文件的大小
            pd.setMax(conn.getContentLength());
            InputStream is = conn.getInputStream();
            File file = new File(Environment.getExternalStorageDirectory(), "updata.apk");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            int total = 0;
            while ((len = bis.read(buffer)) != -1) {
                if (!isDownloading) {
                    break;
                }
                fos.write(buffer, 0, len);
                total += len;
                // 获取当前下载量
                pd.setProgress(total);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            return null;
        }
    }
    
    /*
     * 
     * 弹出对话框通知用户更新程序
     * 
     * 弹出对话框的步骤： 1.创建alertDialog的builder. 2.要给builder设置属性, 对话框的内容,样式,按钮 3.通过builder 创建一个对话框 4.对话框show()出来
     */
    public void showUpdataDialog() {
        AlertDialog.Builder builer = new Builder(this);
        builer.setTitle("版本升级");
        builer.setMessage("当前不是最新版本!");
        // 当点确定按钮时从服务器上下载 新的apk 然后安装
        builer.setPositiveButton("确定", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                downLoadApk();
            }
        });
        // 当点取消按钮时进行登录
        builer.setNegativeButton("取消", new OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                check();
            }
        });
        AlertDialog dialog = builer.create();
        dialog.show();
    }
    
    public void login(String url) {
        aq.ajax(url, JSONObject.class, new AjaxCallback<JSONObject>() {
            @Override
            public void callback(String url, JSONObject json, AjaxStatus status) {
                try {
                    if ("ok".equals(json.getString("status"))) {
                        // Thread.sleep(2 * 1000);
                        SharedPreferences preferences1 =
                            LoadingActivity.this.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
                        String setuppwdstr1 = preferences1.getString(Contact.LOCAL_LOGIN_PWD, "");
                        SharedPreferences preferences =
                            context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
                        Editor editor = preferences.edit();
                        editor.putString("im_user_name", json.optString("im_user_name"));
                        editor.putString("im_user_password", json.optString("im_user_password"));
                        editor.putString("im_appkey", json.optString("im_appkey"));
                        editor.commit();
                        
                        if (setuppwdstr1 != null && !"".equals(setuppwdstr1)) {
                            mainIntent = new Intent(LoadingActivity.this, LoadActivity.class);
                        } else {
                            mainIntent = new Intent(LoadingActivity.this, MainActivity.class);
                        }
               
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                        CMUtil.getInstance(LoadingActivity.this).doLogin();
                        startActivity(mainIntent);
                        finish();
                        
                    } else if ("disabled".equals(json.getString("status"))) {
                        cusi = new ContactUserServiceImpl(context);
                        SharedPreferences preferences =
                            context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
                        Editor editor = preferences.edit();
                        editor.putString("name", "");
                        editor.putString("password", "");
                        editor.putString("user_code", "");
                        editor.putBoolean("isFirstStart", false);
                        editor.putBoolean("isLoginSuccess", false);
                        editor.putString("im_user_name", "");
                        editor.putString("im_user_password", "");
                        editor.commit();
                        cusi.delContact();
                        Utils.SaveIsLogin(LoadingActivity.this, 0);
                        CMIMHelper.getCmAccountManager().doLogOut();
                    } else if ("del".equals(json.getString("status"))) {
                        cusi = new ContactUserServiceImpl(context);
                        SharedPreferences preferences =
                            context.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
                        Editor editor = preferences.edit();
                        editor.putString("name", "");
                        editor.putString("password", "");
                        editor.putString("user_code", "");
                        editor.putBoolean("isFirstStart", false);
                        editor.putBoolean("isLoginSuccess", false);
                        editor.commit();
                        cusi.delContact();
                        Utils.SaveIsLogin(LoadingActivity.this, 0);
                        Utils.showToast(context, "账号已删除！请联系管理员！");
                        mainIntent = new Intent(LoadingActivity.this, LoginForPwdActivity.class);
                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                        
                    } else {
                        Utils.showToast(context, "登录失败！请联系管理员！");
                        finish();
                    }
                } catch (Exception e) {
                	e.printStackTrace();
//                    mainIntent = new Intent(LoadingActivity.this, LoginValidateActivity.class);
//                    Message msg = new Message();
//                    msg.what = 1;
//                    handler.sendMessage(msg);
//                    e.printStackTrace();
                	noNetLogin();
                }
            }
        });
    }
    
    public void noNetLogin() {
    	 SharedPreferences preferences1 =
                 LoadingActivity.this.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
             String setuppwdstr1 = preferences1.getString(Contact.LOCAL_LOGIN_PWD, "");
    	 if (setuppwdstr1 != null && !"".equals(setuppwdstr1)) {
             mainIntent = new Intent(LoadingActivity.this, LoadActivity.class);
         } else {
             mainIntent = new Intent(LoadingActivity.this, MainActivity.class);
         }

         Message msg = new Message();
         msg.what = 1;
         handler.sendMessage(msg);
         startActivity(mainIntent);
         finish();
    }
}
